<?php
/**
 * Created by PhpStorm.
 * User: halobear
 * Date: 2018/12/6
 * Time: 4:51 PM
 */
if (!function_exists('jwt_encode')) {
    /**
     * jwt加密
     *
     * @param array  $data
     * @param int    $exp
     * @param string $key
     * @return string
     */
    function jwt_encode($data = [], $exp = 86400, $key = '')
    {
        $key       = empty($key) ? env('JWT_SECRET') : $key;
        $issued_at = time();
        $token     = [
            "iss"  => 'halobear',
            "jti"  => md5(uniqid($issued_at, true)),
            "iat"  => $issued_at,
            "nbf"  => $issued_at,
            "exp"  => $issued_at + $exp,
            "data" => $data,
        ];

        return \Firebase\JWT\JWT::encode($token, $key);
    }
}

if (!function_exists('jwt_decode')) {
    /**
     * jwt解密
     *
     * @param        $token
     * @param string $key
     * @return array
     */
    function jwt_decode($token, $key = '')
    {
        $key = empty($key) ? env('JWT_SECRET') : $key;

        try {
            $data = \Firebase\JWT\JWT::decode($token, $key, ['HS256']);
        } catch (Exception $e) {
            $data = [];
        }

        return object_array($data);
    }
}

if (!function_exists('object_array')) {
    function object_array($d)
    {
        if (is_object($d)) {
            $d = get_object_vars($d);
        }

        if (is_array($d)) {
            return array_map(__FUNCTION__, $d);
        } else {
            return $d;
        }
    }
}


if (!function_exists('success')) {
    /**
     * @param array  $data
     * @param string $info
     * @return \Illuminate\Http\Response
     */
    function success($data = [], $info = '成功')
    {
        if (is_string($data) && $temp = json_decode($data, 1)) {
            $data = $temp;
        }

        // return ['iRet' => 1, 'info' => $info, 'data' => $data];
        empty($data) && $data = (object)[];

        return response([
            'iRet' => 1,
            'info' => $info,
            'data' => $data,
            'time' => sprintf("%.4f", microtime(true) - LARAVEL_START),
        ]);
    }
}

function dda($model)
{
    if (method_exists($model, 'toArray')) {
        dd($model->toArray());
    } else {
        dd($model);
    }
}

if (!function_exists('write_log')) {
    /**
     * 手动记录日志
     *
     * @param $tag
     * @param $msg
     */
    function write_log($tag, $msg)
    {
        $filename = storage_path() . '/logs/customer' . DIRECTORY_SEPARATOR . $tag . '_' . date('Ymd') . '.log';

        if (!is_string($msg)) {
            $msg = var_export($msg, 1);
        }

        $handler = null;
        if (($handler = fopen($filename, 'ab+')) !== false) {
            fwrite($handler, date('r') . "\t$msg\t" . PHP_EOL);
            fclose($handler);
        }
    }
}